﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace YGBookmark.Models
{
    /// <summary>
    /// 标签实体模型（包含业务验证逻辑）
    /// </summary>
    [Table("Tags")]
    public class Tag
    {
        private const int MaxNameLength = 50;
        private const int MinNameLength = 2;

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }

        //[Required(ErrorMessage = "标签名称不能为空")]
        //[StringLength(MaxNameLength, MinimumLength = MinNameLength,
        //    ErrorMessage = $"标签名称长度需在{MinNameLength}-{MaxNameLength}字符之间")]
        //[Index(IsUnique = true)] // 唯一性约束
        //public string Name { get; set; }

        [Required(ErrorMessage = "标签名称不能为空")]
        [StringLength(50, MinimumLength = 2,
            ErrorMessage = "标签名称长度需在2-50字符之间")]
        public string Name { get; set; }

        [Required]
        [DataType(DataType.DateTime)]
        public DateTime CreateTime { get; set; } = DateTime.Now;

        // 导航属性（多对多关系）
        public virtual ICollection<BookmarkTag> BookmarkTags { get; set; } = new HashSet<BookmarkTag>();

        /// <summary>
        /// 无参构造函数（ORM需要）
        /// </summary>
        public Tag() { }

        /// <summary>
        /// 创建新标签的构造函数
        /// </summary>
        /// <param name="name">规范化的标签名称</param>
        public Tag(string name)
        {
            Name = NormalizeName(name);
        }

        /// <summary>
        /// 名称规范化处理（去除前后空格/小写转换）
        /// </summary>
        private static string NormalizeName(string rawName)
        {
            if (string.IsNullOrWhiteSpace(rawName))
                throw new ArgumentException("标签名称不能为空");

            return rawName.Trim().ToLowerInvariant();
        }

        /// <summary>
        /// 验证标签是否有效
        /// </summary>
        public bool IsValid()
        {
            var context = new ValidationContext(this);
            var results = new List<ValidationResult>();
            return Validator.TryValidateObject(this, context, results, true);
        }

        /// <summary>
        /// 添加关联书签
        /// </summary>
        public void AddBookmark(Bookmark bookmark)
        {
            if (bookmark == null) throw new ArgumentNullException(nameof(bookmark));
            BookmarkTags.Add(new BookmarkTag { TagId = Id, BookmarkId = bookmark.Id });
        }

        /// <summary>
        /// 移除关联书签
        /// </summary>
        public void RemoveBookmark(Bookmark bookmark)
        {
            if (bookmark == null) throw new ArgumentNullException(nameof(bookmark));
            var bookmarkTag = BookmarkTags.FirstOrDefault(bt => bt.BookmarkId == bookmark.Id);
            if (bookmarkTag != null)
            {
                BookmarkTags.Remove(bookmarkTag);
            }
        }

        /// <summary>
        /// 获取标签使用次数
        /// </summary>
        [NotMapped]
        public int UsageCount => BookmarkTags?.Count ?? 0;

        public override string ToString() => $"{Name} ({Id})";
    }
}